package com.example.dao.impl;

import com.example.dao.BlogDao;
import com.example.model.Blog;
import com.example.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 博客数据访问层实现类
 */
public class BlogDaoImpl implements BlogDao {

    @Override
    public int add(Blog blog) {
        String sql = "INSERT INTO t_blog(title, content, category, create_time, update_time, user_id, author_name, view_count) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int generatedId = -1;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, blog.getTitle());
            pstmt.setString(2, blog.getContent());
            pstmt.setString(3, blog.getCategory());
            pstmt.setTimestamp(4, new Timestamp(blog.getCreateTime().getTime()));
            pstmt.setTimestamp(5, new Timestamp(blog.getUpdateTime().getTime()));
            pstmt.setInt(6, blog.getUserId());
            pstmt.setString(7, blog.getAuthorName());
            pstmt.setInt(8, blog.getViewCount());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    generatedId = rs.getInt(1);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return generatedId;
    }

    @Override
    public int delete(int id) {
        String sql = "DELETE FROM t_blog WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return result;
    }

    @Override
    public int update(Blog blog) {
        String sql = "UPDATE t_blog SET title = ?, content = ?, category = ?, update_time = ? WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, blog.getTitle());
            pstmt.setString(2, blog.getContent());
            pstmt.setString(3, blog.getCategory());
            pstmt.setTimestamp(4, new Timestamp(blog.getUpdateTime().getTime()));
            pstmt.setInt(5, blog.getId());
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return result;
    }

    @Override
    public Blog findById(int id) {
        String sql = "SELECT * FROM t_blog WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Blog blog = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                blog = extractBlogFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blog;
    }

    @Override
    public List<Blog> findAll() {
        String sql = "SELECT * FROM t_blog ORDER BY create_time DESC";
        return findBlogsBySQL(sql);
    }

    @Override
    public List<Blog> findByUserId(int userId) {
        String sql = "SELECT * FROM t_blog WHERE user_id = ? ORDER BY create_time DESC";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Blog> blogList = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Blog blog = extractBlogFromResultSet(rs);
                blogList.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blogList;
    }

    @Override
    public List<Blog> findByCategory(String category) {
        String sql = "SELECT * FROM t_blog WHERE category = ? ORDER BY create_time DESC";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Blog> blogList = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, category);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Blog blog = extractBlogFromResultSet(rs);
                blogList.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blogList;
    }

    @Override
    public List<Blog> search(String keyword) {
        String sql = "SELECT * FROM t_blog WHERE title LIKE ? OR content LIKE ? ORDER BY create_time DESC";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Blog> blogList = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + keyword + "%");
            pstmt.setString(2, "%" + keyword + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Blog blog = extractBlogFromResultSet(rs);
                blogList.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blogList;
    }

    @Override
    public List<Blog> findHotBlogs(int limit) {
        String sql = "SELECT * FROM t_blog ORDER BY view_count DESC LIMIT ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Blog> blogList = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, limit);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Blog blog = extractBlogFromResultSet(rs);
                blogList.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blogList;
    }

    @Override
    public boolean incrementViewCount(int id) {
        String sql = "UPDATE t_blog SET view_count = view_count + 1 WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return result > 0;
    }
    
    /**
     * 从ResultSet中提取博客信息
     */
    private Blog extractBlogFromResultSet(ResultSet rs) throws SQLException {
        Blog blog = new Blog();
        blog.setId(rs.getInt("id"));
        blog.setTitle(rs.getString("title"));
        blog.setContent(rs.getString("content"));
        blog.setCategory(rs.getString("category"));
        blog.setCreateTime(rs.getTimestamp("create_time"));
        blog.setUpdateTime(rs.getTimestamp("update_time"));
        blog.setUserId(rs.getInt("user_id"));
        blog.setAuthorName(rs.getString("author_name"));
        blog.setViewCount(rs.getInt("view_count"));
        return blog;
    }
    
    /**
     * 通用方法，根据SQL查询博客列表
     */
    private List<Blog> findBlogsBySQL(String sql) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Blog> blogList = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Blog blog = extractBlogFromResultSet(rs);
                blogList.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return blogList;
    }
} 